const router = require('koa-router')()

router.prefix('/assignment')

// 分组需要用到的方法
function randomGroupAssignment(students, groupSize) {
  const numGroups = Math.ceil(students.length / groupSize);
  const shuffledStudents = shuffleArray(students);
  const groups = new Array(numGroups).fill().map(() => ({ members: [], peerIndex: -1 }));

  let groupIndex = 0;
  let peerIndex = 0; // 设置初始批改小组索引为 0
  for (let i = 0; i < shuffledStudents.length; i++) {
    groups[groupIndex].members.push(shuffledStudents[i]);
    if (groups[groupIndex].members.length === groupSize) {
      // 设置需要批改的小组索引，确保不是自身
      groups[groupIndex].peerIndex = (peerIndex + 1) % numGroups;
      groupIndex++;
      peerIndex++;
    }
  }


  // 检查是否存在未匹配的小组，并为其分配批改小组
  const unassignedGroups = groups.filter(group => group.peerIndex === -1);
  for (let i = 0; i < unassignedGroups.length; i++) {
    // 查找下一个可用的批改小组索引，确保不是自身
    let nextPeerIndex = (peerIndex + 1) % numGroups;
    while (nextPeerIndex === groupIndex) {
      nextPeerIndex = (nextPeerIndex + 1) % numGroups;
    }
    unassignedGroups[i].peerIndex = nextPeerIndex;
    peerIndex++;
  }

  return groups;
}

function shuffleArray(array) {
  // Fisher-Yates 洗牌算法
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

async function distributionGroup(ctx) {
  let course_id = ctx.request.body.course_id;
  let sql = "select student_id from student_course_relation where course_id = ?";
  let res = await ctx.db.EXCUTE(sql, [course_id]);
  console.log(res, "查询结果");
  // 以五个人为一小组
  let groupSize = 5;
  let groups = randomGroupAssignment(res, groupSize);
  console.log(groups);

  let groupIDArr = [];
  for (let i = 0; i < groups.length; i++) {
    let datacenterId = i + 1; // 根据需要设置不同的数据中心ID
    let workerId = i + 1; // 根据需要设置不同的工作器ID
    let id = ctx.snowFlake.createSnow(datacenterId, workerId);
    while (groupIDArr.includes(id)) {
      id = ctx.snowFlake.createSnow(datacenterId, workerId);
    }
    groupIDArr.push(id);
    // console.log(id, "雪花ID");
  }

  let addGroup = "insert into groupinfo (group_id, course_id, group_number) values ";
  let addGroupRelation = "insert into group_student_relation (group_id, student_id) values ";
  let addGroupCorrection = "insert into group_correction (group_id, correction_group) values ";
  let addGroupArr = [];
  let addGroupCorrectionArr = [];
  for (let i = 0; i < groups.length; i++) {
    console.log(`小组 成员:`, groups[i].members);
    console.log(groups[i].peerIndex, "需要批改的小组");
    console.log(groupIDArr[groups[i].peerIndex], "需要批改的小组");
    let sql2 = `('${groupIDArr[i]}', '${groupIDArr[groups[i].peerIndex]}')`

    groups[i].members.push(groupIDArr[i]);
    // console.log(`对应的批改小组:`, peerGroup.members);
    let sql = `('${groupIDArr[i]}', '${course_id}', ${groups[i].members.length - 1})`
    addGroupArr.push(sql);
    console.log(sql2, "sql2");
    addGroupCorrectionArr.push(sql2);
  }

  if (addGroupArr.length > 0) {
    addGroup += addGroupArr.join(", ");
    let res = await ctx.db.EXCUTE(addGroup, []);
    console.log(res);
  }

  if (addGroupCorrectionArr.length > 0) {
    addGroupCorrection += addGroupCorrectionArr.join(", ");
    console.log(addGroupCorrection, "slqdwihioh");
    let res = await ctx.db.EXCUTE(addGroupCorrection, []);
    console.log(res, "返回的是correction表的结果");
  }

  let addGroupRelationArr = [];
  groups.forEach(item => {
    console.log(item, "item");
    for (let i = 0; i < item.members.length - 1; i++) {
      let sql = `(${item.members[item.members.length - 1]}, '${item.members[i].student_id}')`;
      addGroupRelationArr.push(sql);
    }
  })

  if (addGroupRelationArr.length > 0) {
    addGroupRelation += addGroupRelationArr.join(', ');
    console.log(addGroupRelation, "relation");
    let res = await ctx.db.EXCUTE(addGroupRelation, []);
    console.log(res);
  }
}
// 将标准时间转换为YYYY-MM-DD HH:MM:SS类型的
const formTime = (time) => {
  let newtime = new Date(time);
  // console.log(new Date(time), "要进行转换的时间");
  const year = newtime.getFullYear();
  const month = String(newtime.getMonth() + 1).padStart(2, "0");
  const day = String(newtime.getDate()).padStart(2, "0");
  const hours = String(newtime.getHours()).padStart(2, "0");
  const minutes = String(newtime.getMinutes()).padStart(2, "0");
  const seconds = String(newtime.getSeconds()).padStart(2, "0");

  const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return formattedDate;
}
// 添加通知
async function info(ctx) {
  let { teacher_id, course_id, title } = ctx.request.body
  let csql = 'select course_name from course where course_id = ?'
  let cres = await ctx.db.EXCUTE(csql, [course_id])
  let course_name = cres[0].course_name
  let tsql = 'select user_id from teacher where teacher_id = ?'
  let ssql = 'select user_id from student where student_id IN (select student_id from student_course_relation where course_id = ?)'
  let tres = await ctx.db.EXCUTE(tsql, [teacher_id])
  let sender = tres[0].user_id
  console.log('sender', sender);
  let sres = await ctx.db.EXCUTE(ssql, [course_id])
  let msql = 'insert into message (message_id, sender, recipient, content, status, create_time, update_time, type) values '
  let mArr = []
  let groupIDArr = [];
  for (let i = 0; i < sres.length; i++) {
    let datacenterId = i + 1; // 根据需要设置不同的数据中心ID
    let workerId = i + 1; // 根据需要设置不同的工作器ID
    let id = ctx.snowFlake.createSnow(datacenterId, workerId);
    while (groupIDArr.includes(id)) {
      id = ctx.snowFlake.createSnow(datacenterId, workerId);
    }
    groupIDArr.push(id);
    // console.log(id, "雪花ID");
  }
  sres.forEach((item, index) => {
    console.log('recipient', item);
    let mval = `('${groupIDArr[index]}', '${sender}', '${item.user_id}', '新的任务已发布 ${course_name}-${title}', 'unread', '${formTime(new Date())}', '${formTime(new Date())}', 'info')`
    mArr.push(mval)
  })
  if (mArr.length > 0) {
    msql += mArr.join(', ')
    let mres = await ctx.db.EXCUTE(msql, [])
    console.log(mres);
    if (mres.affectedRows != 0) {
      console.log('完成通知');
    } else {
      console.log('通知失败');
    }
  }
}

// 此处是发布作业，在这个地方如果作业发布成功了， 那么就需要给student_submit_assignment表添加属于该任务的每一个学生的提交信息
router.post("/publish", async (ctx, next) => {
  // 现在新添加了提个作业的描述
  // 在添加作业的时候，需要判断该作业属于的课程是否是第一次添加作业， 如果是第一次添加，那么需要为该课程的成员进行分组
  // 添加作业时候如果选择了学生批改的选项，那么就是给每个学生添加一个学生批改记录
  let data = ctx.request.body;
  let numsql = "select count(*) as num from assignment where course_id = ?"
  let resNum = await ctx.db.EXCUTE(numsql, [data.course_id]);
  let teacher_id = data.teacher_id;
  // 判断是否是第一次提交作业，如果是，那么就是进行分组
  // if (resNum[0].num === 0) {
  //   await distributionGroup(ctx);
  // }
  // 判断课程是否正在进行
  let sql = "select start_date, end_date from course where course_id = ?"
  let res = await ctx.db.EXCUTE(sql, [data.course_id]);
  let isStart = Date.now() > new Date(res[0].start_date).getTime() && Date.now() < new Date(res[0].end_date).getTime();
  console.log(isStart, "是否在课程时间内");
  if (isStart) {
    // 添加通知
    // await info(ctx);
    // 生成作业的雪花ID
    let assignment_id = ctx.snowFlake.createSnow(4);
    let sql = "insert into assignment (assignment_id, assignment_title, course_id, grade_id, publish_time, deadline, assignment_status, total_points, publish_number, teacher_id, institute_id, assignment_describe) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    let res = await ctx.db.EXCUTE(sql, [assignment_id, data.title, data.course_id, data.grade_id, data.publishTime, data.deadline, data.status, data.total_points, 0, teacher_id, data.institute_id, data.content]);
    // 生成题目的雪花ID
    let sqlchoice = "insert into choice (question_id, choice_question, answer, question_index, assignment_id, isMutiple, proportion, options_list, question_type) values ";
    let sqlessay = "insert into essayquestion (essayQuestion, answer, question_index, assignment_id, proportion, question_id, question_type) values ";
    let choiceValues = [];
    let essayValues = [];
    // 定义一个ID数组，让其每次生成ID的时候都从中进行筛选判断，那么如果是产生了重复的ID，就不进行存储
    let generatedID = [];
    let length = (data.questions.multipleChoiceQuestions ? data.questions.multipleChoiceQuestions.length : 0) + (data.questions.shortAnswerQuestions ? data.questions.shortAnswerQuestions.length : 0) + (data.questions.singleChoiceQuestions ? data.questions.singleChoiceQuestions.length : 0);
    let Index = 0
    for (let i = 0; i < length; i++) {
      let datacenterId = i + 1; // 根据需要设置不同的数据中心ID
      let workerId = i + 1; // 根据需要设置不同的工作器ID
      let id = ctx.snowFlake.createSnow(datacenterId, workerId);
      while (generatedID.includes(id)) {
        id = ctx.snowFlake.createSnow(datacenterId, workerId);
      }
      generatedID.push(id);
    }
    if (data.questions.singleChoiceQuestions) {
      data.questions.singleChoiceQuestions.forEach((Element, index) => {
        let question_id = generatedID[index + Index];
        let sql = `('${question_id}', '${Element.question}', '${Element.answer ? JSON.stringify(Element.answer) : null}', ${index + 1}, '${assignment_id}', false, ${Element.proportion}, '${JSON.stringify(Element.optionsList)}', '单选题')`;
        choiceValues.push(sql);
      })

    }
    if (data.questions.multipleChoiceQuestions) {
      data.questions.multipleChoiceQuestions.forEach((Element, index) => {
        let question_id = generatedID[index + data.questions.singleChoiceQuestions.length];
        console.log(question_id, "多选题的ID");
        let sql = `('${question_id}', '${Element.question}', '${Element.answer}', ${index + 1}, '${assignment_id}', true, ${Element.proportion}, '${JSON.stringify(Element.optionsList)}', '多选题')`;
        choiceValues.push(sql);
      })

    }
    if (data.questions.shortAnswerQuestions) {
      data.questions.shortAnswerQuestions.forEach((Element, index) => {
        let question_id = generatedID[index + data.questions.singleChoiceQuestions.length + data.questions.multipleChoiceQuestions.length];
        let sql = `('${Element.question}', '${Element.answer}', ${index + 1}, '${assignment_id}', ${Element.proportion}, ${question_id}, "简答题")`;
        essayValues.push(sql);
      })
    }
    if (choiceValues.length > 0) {
      sqlchoice += choiceValues.join(", ");
      let res = await ctx.db.EXCUTE(sqlchoice);
    }
    if (essayValues.length > 0) {
      sqlessay += essayValues.join(", ");
      let res = await ctx.db.EXCUTE(sqlessay);
    }
    // 添加学生的提交信息
    // 定义一个ID数组，让其每次生成ID的时候都从中进行筛选判断，那么如果是产生了重复的ID，就不进行存储
    let studentIdSql = "select student_id from student_course_relation where course_id = ?"
    let studentArr = await ctx.db.EXCUTE(studentIdSql, [data.course_id]);
    let studentSubmitID = [];
    for (let i = 0; i < studentArr.length; i++) {
      let datacenterId = i + 1; // 根据需要设置不同的数据中心ID
      let workerId = i + 1; // 根据需要设置不同的工作器ID
      let id = ctx.snowFlake.createSnow(datacenterId, workerId);
      while (studentSubmitID.includes(id)) {
        id = ctx.snowFlake.createSnow(datacenterId, workerId);
      }
      studentSubmitID.push(id);
    }
    console.log(studentSubmitID);
    let addsql = [];
    studentArr.forEach((item, index) => {
      let sql = `('${studentSubmitID[index]}', '${assignment_id}', '${item.student_id}', 'unpublish', 'false', '${data.course_id}')`
      addsql.push(sql);
    })
    //  这个地方在插入数据的时候需要加上课程ID
    let addStudentSql = "insert into student_submit_assignment (student_assignment_id, assignment_id, student_id, submit_status, correction_status, course_id) values "
    if (addsql.length > 0) {
      addStudentSql += addsql.join(", ");
      let res = await ctx.db.EXCUTE(addStudentSql);
      console.log(res, "添加课程记录成功");
    }

    // 添加学生批改信息
    // 搜索学生所在小组，以及需要批改小组的成员的信息
    // studentArr是属于该课程的学生的信息
    // 先查小组信息，通过小组，查询批改小组
    // studentArr是和groupRes一一对应的 ， groupArr和correctGroupArr一一对应
    // 那么只有当勾选了需要学生批改的选项之后才会执行， 只有当第一次发布作业的时候才会执行

    // if (data.student_correct) {
    //   let selectGroupSql = "select group_student_relation.group_id from group_student_relation join groupinfo on group_student_relation.group_id = groupinfo.group_id where groupinfo.course_id = ? and group_student_relation.student_id in ";
    //   studentArr = studentArr.map(item => item.student_id)
    //   console.log(studentArr);
    //   let groupRes = await ctx.db.EXCUTE(selectGroupSql + `(${studentArr.join(', ')})`, [data.course_id]);
    //   groupRes = groupRes.map(item => item.group_id);
    //   console.log(groupRes, "groupRes");
    //   // 将小组去重
    //   let groupArr = [...new Set(groupRes)];
    //   console.log(groupArr, "groupArr");
    //   let selectCorectGroup = 'select correction_group from group_correction where group_id in '
    //   let correctGroupArr = await ctx.db.EXCUTE(`${selectCorectGroup}(${groupArr.join(", ")})`, []);
    //   correctGroupArr = correctGroupArr.map(item => item.correction_group);
    //   console.log(correctGroupArr, "correctGroupArr");
    //   let insertCorrectionSql = 'insert into student_correction_assignment (student_correction_id, student_id, group_id, assignment_id, corrected_id) values '
    //   let obj = {};
    //   let correct_group = {};
    //   let correct_id_arr = [];
    //   for (let i = 0; i < groupArr.length; i++) {
    //     obj[groupArr[i]] = [];
    //     correct_group[groupArr[i]] = correctGroupArr[i];
    //   }
    //   for (let i = 0; i < studentArr.length; i++) {
    //     obj[groupRes[i]].push(studentArr[i]);
    //   }
    //   console.log(obj, "obj");
    //   for (let i = 0; i < groupRes.length * obj[groupArr[0]].length; i++) {
    //     let datacenterId = i + 1; // 根据需要设置不同的数据中心ID
    //     let workerId = i + 1; // 根据需要设置不同的工作器ID
    //     let id = ctx.snowFlake.createSnow(datacenterId, workerId);
    //     while (correct_id_arr.includes(id)) {
    //       id = ctx.snowFlake.createSnow(datacenterId, workerId);
    //     }
    //     correct_id_arr.push(id);
    //     // console.log(id, "雪花ID");
    //   }
    //   let sqlArr = [];
    //   let allIndex = 0;
    //   let groupIndex = 0;
    //   for (let i in obj) {
    //     obj[i].forEach((item) => {
    //       console.log(correctGroupArr.find(element => element == i));
    //       obj[correctGroupArr[groupIndex]].forEach((element) => {
    //         sqlArr.push(`(${correct_id_arr[allIndex]}, ${item}, ${i}, ${assignment_id}, ${element})`);
    //         console.log(allIndex);
    //         allIndex++
    //       })
    //     })
    //     groupIndex++
    //   }
    //   if (sqlArr.length > 0) {
    //     insertCorrectionSql += sqlArr.join(', ');
    //     console.log(insertCorrectionSql, "sqlYuju");
    //     let res = await ctx.db.EXCUTE(insertCorrectionSql, []);
    //     console.log(res);
    //   }
    // }


    ctx.body = { code: 200 };
  } else {
    ctx.body = { code: 500, msg: "抱歉，该课程还未开始" }
  }
})

// 编辑作业
router.post("/editAssignment", async (ctx, next) => {
  let data = ctx.request.body.data;
  let teacher_id = data.teacher_id;
  let assignment_id = data.assignment_id;
  let sql = "update assignment set assignment_title = ?, assignment_describe = ?, course_id = ?, student_correct = ?, grade_id = ?, publish_time = ?, deadline = ?, comment_disabled = ?, assignment_status = ?, total_points = ?, teacher_id = ?, institute_id = ? where assignment_id = ?";
  let res = await ctx.db.EXCUTE(sql, [data.title, data.content, data.course_id, data.student_correct, data.grade_id, data.publishTime, data.deadline, data.comment_disabled, data.status, data.total_points, teacher_id, data.institute_id, assignment_id]);

  // 由于question_list中的每一个数据都要更新，那么如果进行更新就需要有很多的SQL操作，在此使用临时表对表进行批量更新

  // 那么其实是对于之前存在的数据进行更新，但是对于之前不存在数据而言就是添加操作了
  let sqlchoice = "replace into choice (question_id, choice_question, answer, question_index, assignment_id, isMutiple, proportion, options_list, question_type) values ";
  let sqlessay = "replace into essayquestion (essayQuestion, answer, question_index, assignment_id, proportion, question_id, question_type) values ";

  // 定义一个ID数组，让其每次生成ID的时候都从中进行筛选判断，那么如果是产生了重复的ID，就不进行存储
  let generatedID = [];
  let length = 0;
  for (let i in data.questions) {
    length += data.questions[i].length;
  }

  console.log(length, "123456");
  let Index = 0
  for (let i = 0; i < length; i++) {
    let datacenterId = i + 1; // 根据需要设置不同的数据中心ID
    let workerId = i + 1; // 根据需要设置不同的工作器ID
    let id = ctx.snowFlake.createSnow(datacenterId, workerId);
    while (generatedID.includes(id)) {
      id = ctx.snowFlake.createSnow(datacenterId, workerId);
    }
    generatedID.push(id);
  }

  let choiceValues = [];
  let essayValues = [];
  console.log(data.questions, "questions");
  if (data.questions.singleChoiceQuestions) {
    data.questions.singleChoiceQuestions.forEach((Element, index) => {
      let question_id
      if (Element.question_id) {
        question_id = Element.question_id;
      } else {
        question_id = generatedID[index];
      }
      console.log(Element);
      let sql = `('${question_id}', '${Element.question}', '${Element.answer ? JSON.stringify(Element.answer) : null}', ${index + 1}, '${assignment_id}', false, ${Element.proportion}, '${JSON.stringify(Element.optionsList)}', '单选题')`;
      choiceValues.push(sql);
      console.log(sql);
    })
  }

  if (data.questions.multipleChoiceQuestions) {
    data.questions.multipleChoiceQuestions.forEach((Element, index) => {
      let question_id;
      if (Element.question_id) {
        question_id = Element.question_id;
      } else {
        question_id = generatedID[index + data.questions.singleChoiceQuestions.length]
      }
      console.log(question_id, "多选题的ID");
      let sql = `('${question_id}', '${Element.question}', '${Element.answer}', ${index + 1}, '${assignment_id}', true, ${Element.proportion}, '${JSON.stringify(Element.optionsList)}', '多选题')`;
      choiceValues.push(sql);
    })
  }

  if (data.questions.shortAnswerQuestions) {
    data.questions.shortAnswerQuestions.forEach((Element, index) => {
      let question_id;
      if (Element.question_id) {
        question_id = Element.question_id;
        console.log("有ID");
      } else {
        question_id = generatedID[index + data.questions.singleChoiceQuestions.length + data.questions.multipleChoiceQuestions.length];
      }
      let sql = `('${Element.question}', '${Element.answer}', ${index + 1}, '${assignment_id}', ${Element.proportion}, ${question_id}, "简答题")`;
      essayValues.push(sql);
    })
  }



  if (choiceValues.length > 0) {
    sqlchoice += choiceValues.join(", ");
    let res = await ctx.db.EXCUTE(sqlchoice);
  }

  if (essayValues.length > 0) {
    sqlessay += essayValues.join(", ");
    let res = await ctx.db.EXCUTE(sqlessay);
  }

  ctx.body = { code: 200 }
});

// 获取课程信息，这个里面需要进行约束如果的该课程还没有开课，那么的不能展示出来
router.get("/getCourseOptions", async (ctx, next) => {
  let sql3 = "select teacher_id from teacher where user_id = ?";
  console.log(ctx.query);
  let teacher_id = ctx.query.teacher_id;
  console.log(teacher_id);
  let sql2 = "select * from institute join grade on institute.institute_id = grade.institute_id join course on course.grade_id = grade.grade_id where course.teacher_id = ?";
  let res2 = await ctx.db.EXCUTE(sql2, [teacher_id]);
  console.log(res2)
  res2 = res2.filter(item => {
    return new Date(item.start_date).getTime() < Date.now();
  })
  console.log(res2, "打印出来", res2.length);
  function generateRelations(rows, index = 0, relations = []) {
    console.log("函数执行了吗");
    if (index === rows.length) {
      return relations;
    }

    const currentRow = rows[index];
    const instituteId = currentRow.institute_id;
    const gradeId = currentRow.grade_id;
    const courseId = currentRow.course_id;

    let institute = relations.find((r) => r.value === instituteId);

    if (!institute) {
      institute = { value: instituteId, label: currentRow.institute_name, children: [] };
      relations.push(institute);
    }

    let grade = institute.children.find((g) => g.value === gradeId);
    if (!grade) {
      grade = { value: gradeId, label: currentRow.grade_name, number: currentRow.grade_num, children: [] };
      institute.children.push(grade);
    }

    let courseObj = grade.children.find((c) => c.value === courseId);
    if (!courseObj) {
      courseObj = { value: courseId, label: currentRow.course_name };
      grade.children.push(courseObj);
    }

    return generateRelations(rows, index + 1, relations);
  }
  let sql = "select * from course";
  let obj = generateRelations(res2);
  ctx.body = { code: 200, data: obj };
})

// 定义一个转换时间格式的方法
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

router.get("/getAssignment", async (ctx, next) => {
  console.log(ctx.query);
  console.log(ctx.request.body);
  let teacher_id = ctx.query.teacher_id
  let data = ctx.query;
  let sql = "select assignment_id, assignment.publish_time, assignment.assignment_title, assignment.deadline, assignment.assignment_status, assignment.total_points, assignment.publish_number, teacher.teacher_name, course.course_name from assignment join teacher on assignment.teacher_id = teacher.teacher_id join course on assignment.course_id = course.course_id where assignment.teacher_id = ? limit ? offset ?";
  let totalSql = "select COUNT(*) as num from assignment where teacher_id = ?"
  let totalRes = await ctx.db.EXCUTE(totalSql, [teacher_id]);
  let total = totalRes[0].num;
  console.log(totalRes, total);
  let res = await ctx.db.EXCUTE(sql, [teacher_id, 1 * data.pageSize, data.pageSize * (data.pageNum - 1)]);
  let infoList = res.map(item => {
    item.publish_time = formatDate(item.publish_time);
    return item;
  })
  console.log(infoList);

  ctx.body = { code: 200, data: infoList, total }
});

router.get("/fecthAssignment", async (ctx, next) => {
  console.log(ctx.query);
  console.log("执行冷水帝豪");
  let assignment_sql = "select * from assignment where assignment_id = ?";
  let choice_sql = "select * from choice where assignment_id = ?";
  let essay_sql = "select * from essayquestion where assignment_id = ?"
  // let sql = "select assignment.assignment_id, assignment.assignment_title, assignment.assignment_title, assignment.student_correct, assignment.grade_id, assignment.publish_time, assignment.deadline, assignment.assignment_status, assignment.total_points, choice.choice_question as question, choice.answer, choice.question_index, choice.isMutiple, choice.proportion, choice.options_list from assignment join choice on assignment.assignment_id = choice.assignment_id where assignment.assignment_id = ?";
  // let sql2 = "select assignment.assignment_id, assignment.assignment_title, assignment.assignment_title, assignment.student_correct, assignment.grade_id, assignment.publish_time, assignment.deadline, assignment.assignment_status, assignment.total_points, essayquestion.essayQuestion as qunestion, essayquestion.answer, essayquestion.question_index, essayquestion.proportion, essayquestion.question_type from assignment join essayquestion on assignment.assignment_id = essayquestion.assignment_id where assignment.assignment_id = ?";
  let res = await ctx.db.EXCUTE(assignment_sql, [ctx.query.id]);
  let res1 = await ctx.db.EXCUTE(choice_sql, [ctx.query.id]);
  let res2 = await ctx.db.EXCUTE(essay_sql, [ctx.query.id]);

  console.log(res1, res2);

  let singleChoiceQuestions = res1.filter(item => {
    if (item.question_type === '单选题') {
      return item;
    }
  })
  let multipleChoiceQuestions = res1.filter(item => {
    if (item.question_type === '多选题') {
      return item;
    }
  })
  let shortAnswerQuestions = res2;

  console.log(singleChoiceQuestions, "单选题");

  singleChoiceQuestions.sort((a, b) => a.question_index - b.question_index);
  multipleChoiceQuestions.sort((a, b) => a.question_index - b.question_index);
  shortAnswerQuestions.sort((a, b) => a.question_index - b.question_index);
  let questions = {};
  questions.singleChoiceQuestions = singleChoiceQuestions;
  questions.shortAnswerQuestions = shortAnswerQuestions;
  questions.multipleChoiceQuestions = multipleChoiceQuestions;
  let infoList = res;
  infoList[0].questions = questions;
  console.log(questions.singleChoiceQuestions);
  console.log(infoList, "题卷信息");
  ctx.body = { code: 200, infoList };
})

router.post("/deleteAssignment", async (ctx, next) => {
  let id = ctx.request.body.id;
  let sql1 = 'delete from assignment where assignment.assignment_id = ?';
  let sql2 = 'delete from choice where choice.assignment_id = ?'
  let sql3 = 'delete from essayquestion where essayquestion.assignment_id = ?'
  let sql4 = 'delete from student_correction_assignment where assignment_id = ?'
  let sql5 = 'delete from student_submit_assignment where assignment_id = ?'
  let res1 = await ctx.db.EXCUTE(sql1, [id]);
  let res2 = await ctx.db.EXCUTE(sql2, [id]);
  let res3 = await ctx.db.EXCUTE(sql3, [id]);
  let res4 = await ctx.db.EXCUTE(sql4, [id]);
  let res5 = await ctx.db.EXCUTE(sql5, [id]);
  console.log(res1, "删除的结果");
  console.log(id);

  ctx.body = { code: 200 }
})

router.post("/changeStatus", async (ctx, next) => {
  console.log(ctx.request.body);
  let data = ctx.request.body;
  let sql = 'update assignment set assignment_status = ? where assignment_id = ?';
  let res = await ctx.db.EXCUTE(sql, [data.status, data.id]);
  console.log(res);
  ctx.body = { code: 200 }
})

module.exports = router